package com.itheima.security;

import com.itheima.pojo.User;
import org.aspectj.weaver.bcel.BcelAccessForInlineMunger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: yp
 */
public class SpringSecurityUserService implements UserDetailsService{

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    //点击登录, loadUserByUsername()就是执行.
    //参数username:就是用户在页面上输入的用户名
    //UserDetails 需要封装
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据username查询数据库 获得和用户名对应的User对象(模拟)
         User user =  findByUserName(username);
         if(user == null){
             //没有这个用户, 不能登录, 不能授权
             return null;
         }

        //2.查询数据库, 获得角色, 获得权限, 进行授权(模拟)
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
        grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN")); //赋予ROLE_ADMIN角色
        grantedAuthorityList.add(new SimpleGrantedAuthority("add")); //赋予权限
        grantedAuthorityList.add(new SimpleGrantedAuthority("delete")); //赋予权限

        //3.封装成UserDetails返回 参数1:传入用户名, 参数2:密码(数据库里面的密码, 不是用户输入的密码) 参数3: 权限集合
        //把对象封装好, SpringSecurity自动帮我们做校验 其中密码这里加了{noop} 告诉了SpringSecurity校验的时候, 直接校验 不用加密校验
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username,
                user.getPassword(),
                grantedAuthorityList);
        return userDetails;
    }

    //模拟根据用户名查询数据库(就是数据库的数据)
    private User findByUserName(String username) {
        if("admin".equals(username)){
            User user = new User();
            user.setUsername("admin");
            user.setPassword(encoder.encode("123456"));
            return user;
        }

        return  null;
    }
}
